//
//  ImageListViewController.m
//  ActionExtensionSample
//
//  Created by 冯鸿杰 on 2017/6/6.
//  Copyright © 2017年 Mob. All rights reserved.
//

#import "ImageListViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>

@interface ImageListViewController ()

@property (nonatomic, strong) NSArray *imgUrls;

@end

@implementation ImageListViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.tableView.rowHeight = 100;
    
    //解析JS传递过来的数据
    NSExtensionItem *item = self.extensionContext.inputItems.firstObject;
    NSItemProvider *itemProvider = item.attachments.firstObject;
    if ([itemProvider hasItemConformingToTypeIdentifier:(NSString *)kUTTypePropertyList])
    {
        __weak typeof(self) weakSelf = self;
        [itemProvider loadItemForTypeIdentifier:(NSString *)kUTTypePropertyList
                                        options:nil
                              completionHandler:^(id<NSSecureCoding>  _Nullable item, NSError * _Null_unspecified error) {
                                  
                                  //找到JS返回数据
                                  NSDictionary *jsData = item[NSExtensionJavaScriptPreprocessingResultsKey];
                                  NSArray *imgUrls = jsData[@"imgs"];
                                  
                                  dispatch_async(dispatch_get_main_queue(), ^{
                                      
                                      //设置数据源，刷新表格
                                      weakSelf.imgUrls = imgUrls;
                                      [weakSelf.tableView reloadData];
                                      
                                  });
                                  
                              }];
    }
    
    
    //创建一个关闭按钮
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor blueColor];
    [btn setTitle:@"Close" forState:UIControlStateNormal];
    btn.frame = CGRectMake(0, 0, self.tableView.frame.size.width, 50);
    btn.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [btn addTarget:self action:@selector(closeButtonClickedHandler:) forControlEvents:UIControlEventTouchUpInside];
    self.tableView.tableHeaderView = btn;
}

- (void)closeButtonClickedHandler:(id)sender
{
    [self.extensionContext completeRequestReturningItems:nil completionHandler:nil];
}
    
#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.imgUrls.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *const CellId = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellId];
    if (!cell)
    {
        //创建一个现实图片的单元格
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellId];
        
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, cell.contentView.frame.size.width - 40, tableView.rowHeight - 40)];
        imgView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        imgView.tag = 100;
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        imgView.backgroundColor = [UIColor lightGrayColor];
        [cell.contentView addSubview:imgView];
    }
    
    if (self.imgUrls.count > indexPath.row)
    {
        UIImageView *imgView = [cell.contentView viewWithTag:100];
        NSString *url = self.imgUrls[indexPath.row];
        if ([url hasPrefix:@"data:image/png;base64,"])
        {
            NSString *dataStr = [url substringFromIndex:@"data:image/png;base64,".length];
            NSData *imgData = [[NSData alloc] initWithBase64EncodedString:dataStr options:0];
            imgView.image = [[UIImage alloc] initWithData:imgData];
        }
        else
        {
            imgView.image = nil;
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
               
                NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
                NSIndexPath *curIndexPath = [tableView indexPathForCell:cell];
                if (indexPath.row == curIndexPath.row)
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        imgView.image = [[UIImage alloc] initWithData:imgData];
                        
                    });
                    
                }
            });
            
        }
        
    }
    
    
    return cell;
}

@end
